package spitter.demo;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.*;

import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * @author yanheng
 * @data 2020/1/10 11:26
 */
public class XPathParser {

    private final Document document;
    private boolean validation;
    private EntityResolver entityResolver;
    private Properties variables;
    private XPath xpath;

    public XPathParser(InputStream inputStream) throws Exception {
        this.commonConstructor(false, (Properties)null, (EntityResolver)null);
        this.document = this.createDocument(new InputSource(inputStream));
    }

    public XPathParser(Reader reader) throws Exception {
        this.commonConstructor(false, (Properties)null, (EntityResolver)null);
        this.document = this.createDocument(new InputSource(reader));
    }

    public Document getDocument() {
        return document;
    }

    private Document createDocument(InputSource inputSource) throws Exception {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//            factory.setFeature("http://javax.xml.XMLConstants/feature/secure-processing", true);
//            factory.setValidating(this.validation);
//            factory.setNamespaceAware(false);
//            factory.setIgnoringComments(true);
//            factory.setIgnoringElementContentWhitespace(false);
//            factory.setCoalescing(false);
//            factory.setExpandEntityReferences(true);
            DocumentBuilder builder = factory.newDocumentBuilder();
//            builder.setEntityResolver(this.entityResolver);
            builder.setErrorHandler(new ErrorHandler() {
                @Override
                public void error(SAXParseException exception) throws SAXException {
                    throw exception;
                }

                @Override
                public void fatalError(SAXParseException exception) throws SAXException {
                    throw exception;
                }

                @Override
                public void warning(SAXParseException exception) throws SAXException {
                }
            });
            return builder.parse(inputSource);
        } catch (Exception var4) {
            throw new Exception("Error creating document instance.  Cause: " + var4, var4);
        }


    }

    public void setVariables(Properties variables) {
        this.variables = variables;
    }

    public String evalString(String expression) {
        return this.evalString(this.document, expression);
    }

    public String evalString(Object root, String expression) {
        String result = (String)this.evaluate(expression, root, XPathConstants.STRING);
//        result = PropertyParser.parse(result, this.variables);
        return result;
    }

    public Boolean evalBoolean(String expression) {
        return this.evalBoolean(this.document, expression);
    }

    public Boolean evalBoolean(Object root, String expression) {
        return (Boolean)this.evaluate(expression, root, XPathConstants.BOOLEAN);
    }

    public Short evalShort(String expression) {
        return this.evalShort(this.document, expression);
    }

    public Short evalShort(Object root, String expression) {
        return Short.valueOf(this.evalString(root, expression));
    }

    public Integer evalInteger(String expression) {
        return this.evalInteger(this.document, expression);
    }

    public Integer evalInteger(Object root, String expression) {
        return Integer.valueOf(this.evalString(root, expression));
    }

    public Long evalLong(String expression) {
        return this.evalLong(this.document, expression);
    }

    public Long evalLong(Object root, String expression) {
        return Long.valueOf(this.evalString(root, expression));
    }

    public Float evalFloat(String expression) {
        return this.evalFloat(this.document, expression);
    }

    public Float evalFloat(Object root, String expression) {
        return Float.valueOf(this.evalString(root, expression));
    }

    public Double evalDouble(String expression) {
        return this.evalDouble(this.document, expression);
    }

    public Double evalDouble(Object root, String expression) {
        return (Double)this.evaluate(expression, root, XPathConstants.NUMBER);
    }

    public List<XNode> evalNodes(String expression) {
        return this.evalNodes(this.document, expression);
    }

    public List<XNode> evalNodes(Object root, String expression) {
        List<XNode> xnodes = new ArrayList();
        NodeList nodes = (NodeList)this.evaluate(expression, root, XPathConstants.NODESET);

        for(int i = 0; i < nodes.getLength(); ++i) {
            xnodes.add(new XNode(this, nodes.item(i), this.variables));
        }

        return xnodes;
    }

    public XNode evalNode(String expression) {
        return this.evalNode(this.document, expression);
    }

    public XNode evalNode(Object root, String expression) {
        Node node = (Node)this.evaluate(expression, root, XPathConstants.NODE);
        return node == null ? null : new XNode(this, node, this.variables);
    }

    private Object evaluate(String expression, Object root, QName returnType) {
        try {
            return this.xpath.evaluate(expression, root, returnType);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    private void commonConstructor(boolean validation, Properties variables, EntityResolver entityResolver) {
        this.validation = validation;
        this.entityResolver = entityResolver;
        this.variables = variables;
        XPathFactory factory = XPathFactory.newInstance();
        this.xpath = factory.newXPath();
    }

    public static void main(String[] args) {
        String filePath = "F:\\boco\\SDN\\文件采集资料\\20200103\\CM-PTN-NEL-01-V1.0.0-20200103094100-001.xml";

        try {
            Reader reader = new FileReader(filePath);
            XPathParser xPathParser = new XPathParser(reader);
            Document document = xPathParser.getDocument();
            NodeList objects = document.getElementsByTagName("Objects");
            XNode properties = xPathParser.evalNode("/DataFile");
            System.out.println(properties.evalNode("FileHeader"));
//            System.out.println(properties.evalNode("Objects"));
            XNode objects1 = properties.evalNode("Objects");
            System.out.println(objects1.evalNode("FieldName"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }




}
